package com.dodo.graffiti;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Bitmap.Config;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;

public class GraffitiView extends View {

	private Bitmap mBitmap;
	private Canvas mCanvas;
	private Path mPath;
	private Paint mPaint;
	private int SCREEN_W;
	private int SCREEN_H;
	private float mX, mY;
	private static final float TOUCH_TOLERANCE = 4;

	public GraffitiView(Context context) {
		super(context);
		setFocusable(true);
		DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
		setBackgroundResource(R.drawable.pre2);
		
		SCREEN_W = displayMetrics.widthPixels;
		SCREEN_H = displayMetrics.heightPixels;
		
		mPaint = new Paint();
		mPaint.setAlpha(0);
		mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
		mPaint.setAntiAlias(true);

		mPaint.setDither(true);
		mPaint.setStyle(Paint.Style.STROKE);
		mPaint.setStrokeJoin(Paint.Join.ROUND);
		mPaint.setStrokeCap(Paint.Cap.ROUND);
		mPaint.setStrokeWidth(20);
		
		mPath = new Path();
		
		
		Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.pre7);
		bm = Bitmap.createScaledBitmap(bm, SCREEN_W, SCREEN_H, true);
		
		mBitmap = Bitmap.createBitmap(SCREEN_W, SCREEN_H, Config.ARGB_8888);
		mCanvas = new Canvas();
		mCanvas.setBitmap(mBitmap);
//		mCanvas.drawBitmap(bm, 0, 0, null);
		mCanvas.drawColor(Color.WHITE);
	}

	@Override
	protected void onDraw(Canvas canvas) {
		canvas.drawBitmap(mBitmap, 0, 0, null);
		mCanvas.drawPath(mPath, mPaint);
		super.onDraw(canvas);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		float x = event.getX();
		float y = event.getY();
		
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			startTouch(x, y);
			break;
		case MotionEvent.ACTION_MOVE:
			moveTouch(x, y);
			break;
		case MotionEvent.ACTION_UP:
			endTouch();
			break;
		default:
			break;
		}
		
		invalidate();
		return true;
	}

	private void moveTouch(float x, float y) {
		float dx = Math.abs(x - mX);
		float dy = Math.abs(mY - y);
		
		if(dx > TOUCH_TOLERANCE || dy > TOUCH_TOLERANCE){
			mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2);
			mX = x;
			mY = y;
		}
	}

	private void startTouch(float x, float y) {
		mPath.reset();
		mPath.moveTo(x, y);
		mX = x;
		mY = y;
	}

	private void endTouch() {
		mPath.lineTo(mX, mY);
		mCanvas.drawPath(mPath, mPaint);
	}

}
